package threads;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import runnable.SubmitJob;

import jsonobj.JSonObj;
import jsonobj.JobInfo;

import data.WebSocket;

import utils.SSHUtils;
import utils.Utils;

public class ReceiveThread extends Thread implements JSonObj{
	public static volatile boolean run = true;
	private WebSocket ws;
	private String username;
	

	public ReceiveThread() {
		this.ws = Utils.ws;
		this.username = Utils.username;
	}

	public void run() {
		while (run) {
			try {
				String data = ws.recv();
				
				String[] tokens = data.split("\\|");
				
				byte obj_type = Byte.parseByte(tokens[0]);
				String json = tokens[1];
				
				if(obj_type == PING)
				{
					Utils.ws.send("8|0");
					continue;
				}
				//Utils.out("RECV: " + data);
		        switch(obj_type)
		        {
		        	case CLI_JOB_SUB:
		        	{
		        		JobInfo ji = JobInfo.fromJSon(json);
		        		Utils.out("+ received job submission request: "+data);
		        		Utils.out("+ starting job submit thread");
		        		Utils.exec.execute(new SubmitJob(ji));
		        	}
		        }
			} catch (IOException e) {
				System.out.println(e.getMessage());
				run = false;
			}

		}

	}

	class Cmd implements Runnable {
		String cmd;
		String id;

		public Cmd(String c, String id) {
			this.cmd = c;
			this.id = id;
		}

		public void run() {
			try {
				Process child = Runtime.getRuntime().exec(cmd);
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(child.getInputStream()));
				String s = "";
				String line;
				while ((line = reader.readLine()) != null) {
					System.out.println("Stdout: " + line);
					s += line;
				}
				int exitstatus = child.waitFor();
				ws.send("msg|cmd|" + id + "|" + exitstatus + "|" + s);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
